package cn.backpackerxl.easyJDBC.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: backpackerxl
 * CreateTime: 2022/5/3
 * FileName: StringUtil
 **/
public final class StringUtil {
    private StringUtil() {
    }

    /**
     * 还原驼峰
     *
     * @param humpName 字符串
     * @return 还原驼峰的字符串
     */
    public static String addHump(String humpName) {
        return replace(humpName, Pattern.compile("_(\\w)"), $ -> $.substring(1).toUpperCase(Locale.ROOT));
    }

    /**
     * 判断字符串是否为空
     *
     * @param str 字符串
     * @return boolean
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    /**
     * 去掉驼峰
     *
     * @param humpName 字符串
     * @return 去掉驼峰的字符串
     */
    public static String removeHump(String humpName) {
        return replace(humpName, Pattern.compile("([A-Z])"), $ -> "_" + $.toLowerCase(Locale.ROOT));
    }

    /**
     * 去掉尾部
     *
     * @param str 字符串
     * @return 处理后的字符串
     */
    public static String tail(String str) {
        return str.length() == 0 ? null : str.substring(0, str.length() - 1);
    }

    /**
     * 首字母大写
     *
     * @param str 字符串
     * @return 处理后的字符串
     */
    public static String headBig(String str) {
        return str.length() == 0 ? null : str.substring(0, 1).toUpperCase(Locale.ROOT) + str.substring(1);
    }

    /**
     * 首字母小写
     *
     * @param str 字符串
     * @return 处理后的字符串
     */
    public static String headSmall(String str) {
        return str.length() == 0 ? null : str.substring(0, 1).toLowerCase(Locale.ROOT) + str.substring(1);
    }

    /**
     * 高级替换
     *
     * @param target   替换字符
     * @param pattern  正则
     * @param replacer 替换函数
     * @return 替换后的字符
     */
    public static String replace(String target, Pattern pattern, IReplacer replacer) {
        Matcher matcher = pattern.matcher(target);
        String res = target;
        while (matcher.find()) {
            res = res.replace(matcher.group(), replacer.doWithString(matcher.group()));
        }
        return res;
    }

    /**
     * 通过流对象转化为字符串
     *
     * @param url 路径
     * @return 流对象内容
     */
    public static String getStreamString(URL url) throws IOException {
        StringBuilder res = new StringBuilder();
        File file = new File(url.getFile());
        List<String> list = Files.readAllLines(Paths.get(file.getAbsolutePath()));
        list.forEach(res::append);
        return res.toString();
    }
}
